package com.scalar.chiptrack.sales.actions.quote;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.tags.attachFileTag;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.alarms.Alarm;
import com.scalar.chiptrack.alarms.AlarmUser;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.dao.AttachFileDAO;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.*;
import com.scalar.chiptrack.sales.actions.SalesOrderAction;
import com.scalar.chiptrack.sales.dao.*;
import com.scalar.chiptrack.sales.dao.quote.QuotationDAO;
import com.scalar.chiptrack.sales.forms.quote.QuotationForm;
import com.scalar.chiptrack.sales.forms.ApproverOrderForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.StringUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create Quotation
 *
 * @author Basha
 * @version $Revision: 1.26 $ $Date: 2004/02/07
 */

public final class TransferQuotationAction extends ChipTrackAction
{

    private static final String ACTION_NAME = "/transferQuotation.do"; // TBD
    int isSample = 1;

    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
            throws Exception
    {

        QuotationForm subform = ( QuotationForm ) form;
        HttpSession session = request.getSession ();

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        String action = request.getParameter ( "action" );
        if ( user == null )
        {
            if( "printTransferQuote".equals ( action ) )
            {
                request.setAttribute ( "closeWindowAfterSessionExp", "true" );
			    return ( mapping.findForward( "printTransferQuote" ) );
            }
            else{
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
                return ( mapping.findForward ( "login" ) );
            }
        }

        HashMap errors = new HashMap ();
        HashMap info = new HashMap ();

        String customerId = request.getParameter ( "customerId" );
        Quotation quotationFromMap = null;
        HashMap  quotationMap = ( HashMap ) session.getAttribute( "quotationMap" );

        if ( customerId != null )
        {
             if ( quotationMap != null )
             {
                    quotationFromMap = ( Quotation ) quotationMap.get( customerId );
                    if( quotationFromMap == null )
                    {
                        quotationMap.put( customerId, new Quotation() );
                    }
                }
        }

        if ( "UpdateSalesOrder".equals ( action ) )
        {
            addNewSalesTaxState ( request, session, errors, subform );
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, quotationFromMap.getShippingAddresses(), quotationFromMap );
            }
            subform.setShippingMethod ( subform.getShippingAccount () );
            request.setAttribute ( "QuotationForm", subform );
            ArrayList lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info );
            request.setAttribute ( "lineItems", lineItems );

            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );

            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            if ( subform.getOdmId() > 0 )
            {
                quotationFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
            }
            else
            {
                quotationFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomerId ())) ;
            }
            quotationFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm ( subform.getCustomerId(), subform.getOdmId()  ) );
            errors = ( HashMap ) request.getAttribute ( "Errors" );

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
            }

            saveToken ( request );

            return ( mapping.findForward ( "Quotation" ) );
        }
        else if ( "SubmitSalesOrder".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) ) {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, quotationFromMap.getShippingAddresses(), quotationFromMap );
                session.removeAttribute ( "newShippingAddressId" );
            }

            addNewShippingMethod ( request, session, errors, info, subform, quotationFromMap );
            addNewSalesTaxState ( request, session, errors, subform );
            QuotationAction.addNewShippingTerms ( request, session, errors, info, subform );
            QuotationAction.addNewDeliveryTerms ( request, session, errors, info, subform );
            QuotationAction.addNewShippingInstructions ( request, session, errors, info, subform );
            QuotationAction.addNewFreightInstructions( request, session, errors, info, subform );

            session.setAttribute ( "QuotationForm", subform );

            if ( subform.getOdmId() > 0 )
            {
                quotationFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
            }
            else
            {
                quotationFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomerId ())) ;
            }

            ArrayList lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info );
            session.setAttribute ( "lineItems", lineItems );

            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );

            subform.setTotalQty ( Integer.parseInt ( ( String ) request.getAttribute ( "totalQty" ) ) );
            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            session.setAttribute ( "totalQty", request.getAttribute ( "totalQty" ) );
            session.setAttribute ( "salesTax", request.getAttribute ( "salesTax" ) );
            session.setAttribute ( "subTotal", request.getAttribute ( "subTotal" ) );
            session.setAttribute ( "orderTotal", Double.toString ( subform.getSalesTaxAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSubTotalAsDouble () ) );
            session.setAttribute ( "tempShippingMethod", subform.getShippingMethod () );

            subform.setOdm( CustomerDAO.getCustomerName( null, subform.getOdmId() ) );
            subform.setEndCustomer( CustomerDAO.getCustomerName( null, subform.getEndCustomerId() ));

            String salesOrderNos = null;
            if ( subform.getCustomerPO() != null && subform.getCustomerPO().trim().length() > 0 )
            {
                salesOrderNos = NewSalesOrderDAO.getSalesOrderNoForCustomerPO( null, subform.getCustomerPO(), subform.getCustomerId(), subform.getQuotationNo() );
            }
            if ( salesOrderNos != null && salesOrderNos.trim().length() > 0 )
            {
                if ( salesOrderNos.indexOf(",") > 0 )
                {
                    info.put( "Warning : Sales Orders ( "+salesOrderNos+" ) are already exists for this PO. Do you want to create another ?", null );
                }
                else
                {
                    info.put( "Warning : Sales Order ( "+salesOrderNos+" ) is already generated for this PO. Do you want to create another ?", null );
                }
            }
            request.setAttribute ( "QuotationForm", subform );
            errors = ( HashMap ) request.getAttribute ( "Errors" );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                return ( mapping.findForward ( "Quotation" ) );
            }

            info = ( HashMap ) request.getAttribute ( "Info" );
            if ( !info.isEmpty () )
            {
                request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
            }

            saveToken ( request );

            return ( mapping.findForward ( "ConfirmQuotation" ) );
        }
        else if ( "printTransferQuote".equals ( action ) )
        {

            ApproverOrderForm approverOrderForm = new ApproverOrderForm ();
            Quotation quotation = new Quotation ();
            SalesOrder salesOrder = new SalesOrder();
            QuotationForm quotationForm = ( QuotationForm ) session.getAttribute ( "QuotationForm" );

            PropertyUtils.copyProperties ( salesOrder, quotationForm );

            Customer customer = new Customer();
            customer.setCustomerId( salesOrder.getCustomerId() );
            CustomerDAO.getCustomerDetailsForAcknowledgement( null, customer );
            request.setAttribute ( "customer", customer );

            QuotationDAO.loadClientAddress ( quotation );

            salesOrder.setShippingAddressAsObject( CustomerDAO.getAddressWithContactPersonDetails( salesOrder.getShippingAddressId(), salesOrder .getShippingContactPerson()) );
            salesOrder.setBillingAddressAsObject( CustomerDAO.getAddressWithContactPersonDetails( salesOrder.getBillingAddressId(), salesOrder.getBillingContactPerson(), salesOrder.getCustomerId() ) );

            salesOrder.setShippingAccount ( ( String ) session.getAttribute ( "tempShippingMethod" ) );
            salesOrder.setTotalQty ( ( String ) session.getAttribute ( "totalQty" ) );
            salesOrder.setFinalSubTotal ( Double.parseDouble ( ( String ) session.getAttribute ( "subTotal" ) ) );
            salesOrder.setFinalSalesTax ( Double.parseDouble ( ( String ) session.getAttribute ( "salesTax" ) ) );
            salesOrder.setFinalOrderTotal ( Double.parseDouble ( ( String ) session.getAttribute ( "orderTotal" ) ) );

            approverOrderForm.setSalesOrderNo( quotationForm.getQuotationNo() );
            String clientaddressId =  UserDAO.getClientAddressId();
            String addressId = null;
            String clientname = null;
            String returnVal  = "";
            int finalAddressId = 0;
            if(clientaddressId != null)
            {
                StringTokenizer st = new StringTokenizer(clientaddressId,"@");
                try
                {
                    addressId = st.nextToken();
                    clientname = st.nextToken();
                }catch(NoSuchElementException e)
                {
                     clientname  = "";
                }
            }
            if(addressId  != null)
            {
                finalAddressId = Integer.parseInt(addressId);
            }
            Address clientAddress= UserDAO.loadClientAddressDetails( null , finalAddressId );

            salesOrder.setClientAddressAsObject(clientAddress);
            String clientAddress1 = SalesOrder.getClientAddressAsString(clientAddress);
            salesOrder.setClientAddress(clientAddress1);
            salesOrder.setClientName(clientname);

            salesOrder.setNewEndUserName(quotationForm.getNewEndUserName());
            salesOrder.setNewEndCustomerName(quotationForm.getNewEndCustomerName());

            salesOrder.setSalesOrderNo( quotationForm.getQuotationNo() );
            salesOrder.setSalesOrderDate(quotationForm.getQuotationDate());
            approverOrderForm.setSalesOrder( salesOrder );


            request.setAttribute ( "approverOrderForm", approverOrderForm );
            request.setAttribute ( "lineItems", session.getAttribute ( "lineItems" ) );


            ArrayList list = (ArrayList) request.getAttribute("lineItems");
            if ( list != null )
            {
                Collections.sort (list , new PackingSlipComparator () );
            }

            request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );

            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals( list ) );
            returnVal = "printTransferQuote" ;

             return ( mapping.findForward ( returnVal ) );
        }
        else if ( "EditSalesOrder".equals ( action ) )
        {
            if ( !isTokenValid ( request ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, null );
            }

            resetToken ( request );

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                return ( mapping.findForward ( "successQuotation" ) );
            }

            request.setAttribute ( "QuotationForm", session.getAttribute ( "QuotationForm" ) );

            subform.setShippingMethod ( subform.getShippingAccount () );
            quotationFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm ( subform.getCustomerId(), subform.getOdmId()  ) );
            session.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
            session.setAttribute ( "freightInstructions" , NewSalesOrderDAO.loadFreightInstructions( null ) );
            String hdnShippingMethodName = request.getParameter ( "hdnShippingMethodName" );
            String hdnshippingAccount = request.getParameter ( "hdnshippingAccount" );

            request.setAttribute ( "Account", hdnshippingAccount );
            request.setAttribute ( "Method", hdnshippingAccount );

            request.setAttribute ( "lineItems", ( ArrayList ) request.getAttribute ( "lineItems" ) );
            session.setAttribute ( "maxLineItemNo", session.getAttribute ( "maxLineItemNo" ) );
            saveToken ( request );

            return ( mapping.findForward ( "Quotation" ) );
        }
        else if ( "ConfirmSalesOrder".equals ( action ) )
        {
            if ( !isTokenValid ( request ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, null );
            }

            resetToken ( request );

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                return ( mapping.findForward ( "successQuotation" ) );
            }

            SalesOrder salesOrder       = new SalesOrder();
            QuotationForm quotationForm = ( QuotationForm ) session.getAttribute ( "QuotationForm" );
            String method               = "";
            String account              = "";
            String temp                 = null;
            try
            {
                PropertyUtils.copyProperties ( salesOrder, quotationForm );
            }
            catch ( Exception ex )
            {
                System.out.println ( "copyProperties.....:" + ex );
            }

            salesOrder.setSalesOrderId ( quotationForm.getQuotationId () );
            salesOrder.setSalesOrderNo ( quotationForm.getQuotationNo () );
            salesOrder.setSalesOrderDate ( quotationForm.getQuotationDate () );

            temp = salesOrder.getShippingAccount ();
            account = temp;
            if ( temp != null )
            {
                int index1 = temp.indexOf ( "#" );

                if ( index1 != -1 && index1 != 0 )
                {
                    method = temp.substring ( 0, index1 ).trim();
                    account = temp.substring ( index1 + 1, temp.length() ).trim();
                }
            }
            salesOrder.setShippingMethod ( salesOrder.getShippingMethod().trim() );
            salesOrder.setShippingAccount ( account );

            if ( SalesOrderDAO.isSalesOrderNoExists ( salesOrder.getSalesOrderNo () ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, null );
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );

                request.setAttribute ( "QuotationForm", session.getAttribute ( "QuotationForm" ) );

                request.setAttribute ( "lineItems", ( ArrayList ) request.getAttribute ( "lineItems" ) );
                session.setAttribute ( "maxLineItemNo", session.getAttribute ( "maxLineItemNo" ) );

                request.setAttribute ( "Account", subform.getShippingAccount () );
                request.setAttribute ( "Method", subform.getShippingAccount () );

                saveToken ( request );

                return ( mapping.findForward ( "Quotation" ) );
            }

            salesOrder.setQuotationId( quotationForm.getQuotationId () );
            salesOrder.setQuotationNo( QuotationDAO.loadQuotationNo( null, quotationForm.getQuotationId() ) );
            salesOrder.setNewEndUserName(quotationForm.getNewEndUserName());
            salesOrder.setNewEndCustomerName(quotationForm.getNewEndCustomerName());
            DBTransaction dbTransaction = null;
            boolean success         = false;
            Alarm alarm             = null;
            String status           = null;
            String holdsAuditTrail  = "";
            String salesOrderStatus = null;

            try
            {
                int salesOrderId            = -1;
                int lineItemCount           = 0;
                int taxableLineItemsCount   = 0;
                double closedSubTotal;
                double quoteSubTotal;
                String contactPerson        = null;
                ArrayList lineItems         = null;
                ArrayList transferLineItems = new ArrayList();
                ArrayList closeLineItems    = new ArrayList();
                Iterator items              = null;
                LineItem lineItem           = null;

                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();

                salesOrder.setIsSample ( ( isSample == 0 ) ? true : false );
                salesOrder.setEnteredById ( user.getUserId () );
                salesOrder.setEnteredByName ( user.getFirstName () + " " + user.getLastName () );
                salesOrder.setSalesOrderId ( -1 );

                lineItems =  ( ArrayList ) session.getAttribute ( "lineItems" );
                items = lineItems.iterator();
                while ( items.hasNext() )
                {
                    lineItem = ( LineItem ) items.next();
                    if ( lineItem.getIsTransfer() )
                    {
                        lineItem.setQuotationLineItemId( lineItem.getLineItemId() );
                        transferLineItems.add( lineItem );
                        if ( lineItem.getIsTaxable() )
                        {
                            taxableLineItemsCount++;
                        }
                        lineItemCount++;
                    }
                    if ( lineItem.getIsClose() )
                    {
                        closeLineItems.add( lineItem );
                    }
                }
                if ( taxableLineItemsCount == 0 )
                {
                    salesOrder.setSalesTaxType("0");
                }
                setSalesOrderSubTotals ( salesOrder, lineItems );

                if( lineItemCount > 0)
                {
                    salesOrderId = SalesOrderDAO.saveSalesOrder ( dbTransaction, salesOrder );
                    salesOrder.setSalesOrderId ( salesOrderId );
                    salesOrder.setEnteredDate ( StringUtils.formatDateToString ( new Date ( System.currentTimeMillis () ) ) );
                    contactPerson = salesOrder.getContactPerson ();
                    if ( contactPerson.equals ( salesOrder.getCustomerName () ) )
                    {
                        SalesOrderDAO.updateAddress ( dbTransaction, salesOrder.getSalesOrderId (), salesOrder.getPhoneNumber (), salesOrder.getFaxNumber (), salesOrder.getEmail (), salesOrder.getContactPerson () );
                    }
                    else
                    {
                        CustomerDAO.updateContactPersonDetails (dbTransaction, salesOrder.getCustomerId(),salesOrder.getContactPerson(),
                                                        salesOrder.getPhoneNumber(),
                                                        salesOrder.getCellNumber(),
                                                        salesOrder.getFaxNumber(),
                                                        salesOrder.getEmail (),
                                                        "");
                    }
                    SalesOrderDAO.insertLineItems( dbTransaction , salesOrderId , transferLineItems , user.getUserId() , false);

                    QuotationDAO.transferQuotationLineItems ( dbTransaction, salesOrderId, salesOrder.getQuotationId(), lineItems, user.getUserId() );

                    alarm = SalesOrderDAO.createAlarm ( dbTransaction, user, salesOrder, request.getHeader ( "HOST" ) );

                    holdsAuditTrail = SalesOrderDAO.setCustomerHolds( dbTransaction, user, transferLineItems, salesOrder.getCustomerId(), salesOrder.getSalesOrderId(), salesOrder.getIsSample() );
                    status = SalesDAO.loadOrderStatus ( dbTransaction, salesOrderId );

                    SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), "Created new sales order" + holdsAuditTrail , "###" + salesOrder.getComments () );
                }
                QuotationDAO.closeLineItems( dbTransaction, closeLineItems, user.getUserId() );

                closedSubTotal = getClosedLineItemsSubTotal(lineItems);
                quoteSubTotal = salesOrder.getSubTotalAsDouble() + closedSubTotal;

                QuotationDAO.updateQuoteSubTotal ( dbTransaction, quotationForm.getQuotationId (), quoteSubTotal );
                QuotationDAO.updateQuoteSalesTax ( dbTransaction, quotationForm.getSalesTaxType (), lineItems, quotationForm.getQuotationId() );

                success = true;

                request.setAttribute ( "salesOrderId", Integer.toString ( salesOrderId ) );
                request.setAttribute ( "salesOrderNo", salesOrder.getSalesOrderNo () );
            }
            catch ( ScalarException se )
            {
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Sales Order Details " );
                session.setAttribute ( SessionKeys.ERROR_REPORT, se );
            }
            finally
            {
                if ( success == true )
                {
                    dbTransaction.commit ();
                    try {
                        String filesubgroupauto = request.getParameter(attachFileTag.PARAM_FILE_SUB_GROUP_AUTO);
                        if(filesubgroupauto != null && filesubgroupauto.trim().length() > 0) {
                            AttachFileDAO.updateFileSubGroup(null, filesubgroupauto, salesOrder.getSalesOrderNo());
                        }
                    } catch (Exception e) {
                        errors.put("Error in attaching files", "Please attach again");
                    }
                    if ( isSample == 1 )
                    {
                        if ( salesOrder.getSalesOrderId() != -1)
                        {
                            if ( status.trim ().length () == 0 )
                            {
                                errors.put ( "SalesOrder = " + salesOrder.getSalesOrderNo (), "Saved and Approved Successfully" );
                            }
                            else
                            {
                                errors.put ( "SalesOrder = " + salesOrder.getSalesOrderNo (), "Saved Successfully" );
                            }

                            //errors.put ( "Email ", " has been sent to all approvers" );
                            errors.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();'onmouseover=\"window.status='Click here to View/print Quatation';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Sales Order Details" );
                        }
                        else
                        {
                            errors.put ( "Sales Order ", " not created as no Line Items are selected to transfer." );
                        }
                    }
                    else
                    {
                        if ( salesOrder.getSalesOrderId() != -1)
                        {
                            if ( status.trim ().length () == 0 )
                            {
                                errors.put ( "SampleOrder = " + salesOrder.getSalesOrderNo (), "Saved and Approved Successfully" );
                            }
                            else
                            {
                                errors.put ( "SampleOrder = " + salesOrder.getSalesOrderNo (), "Saved Successfully" );
                            }
                            //errors.put ( "Email ", " has been sent to all approvers" );
                            errors.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();'onmouseover=\"window.status='Click here to View/print Quatation';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Sample Order Details" );
                        }
                        else
                        {
                            errors.put ( "Sales Order ", " not created as no Line Items are selected to transfer." );
                        }
                    }

                    try
                    {
                        if ( salesOrder.getSalesOrderId() != -1)
                        {
                            //alarm.setRecipients ( AlarmDAO.loadRecipientsWithBoardKitChipAccess ( Integer.parseInt ( ( String ) request.getAttribute ( "salesOrderId" ) ), alarm ) );
                            if ( salesOrder.getSalesPerson() != null && salesOrder.getSalesPerson().length() > 0 )
                            {
                                SalesPerson salesPerson = NewCustomerDAO.getSalesPersonDetails( null, salesOrder.getSalesPerson() );
                                if ( salesPerson != null && salesPerson.isSalesAckMail() )
                                {
                                    if ( salesPerson.getAddress() != null && salesPerson.getAddress().getEmail() != null && salesPerson.getAddress().getEmail().trim().length() > 0 )
                                    {
                                        alarm.addRecipient ( new AlarmUser( salesPerson.getSalesPerson (), salesPerson.getAddress().getEmail().trim() ) );
                                    }
                                }
                            }
                            salesOrderStatus = SalesDAO.loadStatus( null, salesOrder.getSalesOrderId() );
                            if( salesOrderStatus != null && salesOrderStatus.indexOf( Constants.SALESORDER_STATUS_HOLD ) >= 0  )
                            {
                                salesOrderStatus = Constants.SALESORDER_STATUS_HOLD;
                            }
                            alarm.setSubject( "Sales Order Notification - SO No.: " + salesOrder.getSalesOrderNo() + " - Customer: " + salesOrder.getCustomerName() + " - Status: " + salesOrderStatus + " -- ACTIVATED" );

                            alarm.notifyAllRecipients ( salesOrder.getHtmlView () );

                            if( status.trim ().length () == 0 )
                            {
                                SalesDAO.updateAlarmAndSendMailWithChangeSummary ( "", salesOrder.getSalesOrderId() , true, user, "" );
                            }

                            SalesOrderHelper.notifyApprovedSalesOrderInfo ( salesOrder.getSalesOrderId() );
                            //SalesOrderHelper.notifyFinanceReasonCode ( salesOrder.getSalesOrderId() );
                            errors.put ( "Email ", " has been sent to all approvers" );
                        }
                    }
                    catch ( Exception e )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SENDING_MAILS_TO_APPROVERS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Send Mail to all Approvers " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, e );
                    }
                }
                else
                {
                    dbTransaction.rollback ();

                    if ( isSample == 1 )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Sales Order Details " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                    }
                    else
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Sales Order Details " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                    }
                }
            }

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.MESSAGES, errors );
            }
            session.removeAttribute ( "lineItems" );
            session.removeAttribute ( "lineItemsWithSubtotals" );
            session.removeAttribute ( "shippingMethods" );
            session.removeAttribute ( "QuotationForm" );
            session.removeAttribute ( "maxLineItemNo" );
            session.removeAttribute ( "shippingInstructions" );
            session.removeAttribute ( "allShippingTerms" );
            session.removeAttribute ( "allDeliveryTerms" );

            quotationMap.remove( salesOrder.getCustomerId()+"" );
        }
        else if ( "loadEndUserDetails".equals ( action ) )
        {
            String endUserId = request.getParameter ( "endUserId" );
            int quotationId = Integer.parseInt(request.getParameter ( "quotationId" ));
            ArrayList lineItems = null;
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
            if ( endUserId != null )
            {
                if ( "".equals ( endUserId.trim () ) )
                {
                    Quotation quotation = QuotationDAO.getQuotationCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );
                    subform.setContactPersons ( quotation.getContactPersons () );
                    subform.setContactPersonsForBillingAddress ( quotation.getContactPersonsForBillingAddress () );
                    subform.setContactPersonsForShippingAddress ( quotation.getContactPersonsForShippingAddress () );
                    subform.setBillingAddress ( SalesOrder.getAddressAsString ( quotation.getBillingAddressAsObject () ));
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( quotation.getShippingAddressAsObject () ));

                    HashMap billingAddressMap = CustomerDAO.getAddressDetailsMap ( quotation.getBillingAddressId() , quotation.getBillingAddressAsObject ());
                    Address quotationAddress = QuotationDAO.getQuotationAddress ( null,quotationId );
                    Address address= CustomerDAO.getAddress ( quotation.getBillingAddressId () );
                    if( quotationAddress != null )
                    {
                        address.setPhoneNumber(quotationAddress.getPhoneNumber());
                        address.setCellNumber("");
                        address.setFaxNumber(quotationAddress.getFaxNumber());
                        address.setEmail(quotationAddress.getEmail());
                    }
                    address.setContactPerson(subform.getCustomerName());
                    address.setCellNumber("");

                    billingAddressMap.put("",SalesOrder.getAddressAsString(address));
                    session.setAttribute ( "billingAddressMap", billingAddressMap  );
                    HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap ( quotation.getShippingAddressId() , quotation.getShippingAddressAsObject ());
                    Address shipAddress = CustomerDAO.getAddress ( quotation.getShippingAddressId () );
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    session.setAttribute ( "shippingAddressMap", shippingAddressMap );
                    subform.setShippingAddresses ( quotation.getShippingAddresses () );
                    subform.setEndUser ( "" );
                    subform.setBillingAddressId ( quotation.getBillingAddressId () );
                    subform.setShippingAddressId ( quotation.getShippingAddressId () );
                    subform.setBillingContactPerson ( quotation.getBillingContactPerson () );
                    subform.setShippingContactPerson ( quotation.getShippingContactPerson () );
                    session.setAttribute ( "mfgPartsWithCustomerPartNos", NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                    session.setAttribute ( "mfgPartsWithLabelNumbers", NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                }
                else
                {
                    EndUser endUser = EndUserDAO.getEndUserDetails ( Integer.parseInt ( endUserId ) );
                    subform.setContactPersonsForBillingAddress(CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultBillingAddressId() ));
                    subform.setContactPersonsForShippingAddress(CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultShippingAddressId() ));
                    subform.setEndUser ( endUser.getEndUserName () );
                    subform.setOdmId(-1);
                    ArrayList shippingAddresses = endUser.getShippingLocations ();
                    shippingAddresses.add ( 0, endUser.getShippingAddress () );

                    subform.setBillingAddressId ( endUser.getDefaultBillingAddressId () );
                    subform.setShippingAddressId ( endUser.getDefaultShippingAddressId () );
                    subform.setBillingAddress ( SalesOrder.getAddressAsString ( endUser.getBillingAddress () ) );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( endUser.getShippingAddress () ) );
                    Quotation quotation = QuotationDAO.getQuotationCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );

                    subform.setBillingContactPerson(endUser.getBillingContactPersonObject().getContactPerson());
                    subform.setShippingContactPerson(endUser.getShippingContactPersonObject().getContactPerson());
                    subform.setContactPersons ( quotation.getContactPersons () );
                    HashMap billingAddressMap = CustomerDAO.getAddressDetailsMap (  subform.getBillingAddressId() , endUser.getBillingAddress ());
                    Address customerAddressObject = CustomerDAO.getAddress ( quotation.getBillingAddressId () );
                    Address quotationAddress = QuotationDAO.getQuotationAddress ( null,quotationId );
                    Address billAddress = CustomerDAO.getAddress ( endUser.getDefaultBillingAddressId () );
                    String billContactPersonName = billAddress.getContactPerson();
                    if( quotationAddress != null)
                    {
                        billAddress.setPhoneNumber(quotationAddress.getPhoneNumber());
                        billAddress.setFaxNumber(quotationAddress.getFaxNumber());
                        billAddress.setEmail(quotationAddress.getEmail());
                    }
                    else
                    {
                        billAddress.setPhoneNumber(customerAddressObject.getPhoneNumber());
                        billAddress.setFaxNumber(customerAddressObject.getFaxNumber());
                        billAddress.setEmail(customerAddressObject.getEmail());
                    }
                    billAddress.setContactPerson(subform.getCustomerName());
                    billAddress.setCellNumber("");

                    billingAddressMap.put("",SalesOrder.getAddressAsString(billAddress));
                    session.setAttribute ( "billingAddressMap", billingAddressMap  );
                    if( billContactPersonName == null || billContactPersonName.trim().length() == 0  || billContactPersonName.equals(subform.getCustomerName() ) )
                    {
                        subform.setBillingAddress(SalesOrder.getAddressAsString(billAddress));
                    }
                    HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap ( subform.getShippingAddressId() , endUser.getShippingAddress ());
                    Address shipAddress = CustomerDAO.getAddress(endUser.getDefaultShippingAddressId());
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    session.setAttribute ( "shippingAddressMap", shippingAddressMap  );
                    Address address = endUser.getBillingAddress();

                    String billAddressWithoutContactPerson = SalesOrderAction.getAddressAsString(address);


                    address = endUser.getShippingAddress();

                    String shipAddressWithoutContactPerson =  SalesOrderAction.getAddressAsString(address);

                    if ( billAddressWithoutContactPerson.trim ().equals ( "" ) )
                    {

                        subform.setBillingAddressId ( quotation.getBillingAddressId () );
                        Address billingAddress = quotation.getBillingAddressAsObject ();
                        subform.setBillingAddress ( SalesOrder.getAddressAsString ( billingAddress ) );
                        subform.setContactPersonsForBillingAddress ( quotation.getContactPersonsForBillingAddress () );
                        subform.setBillingContactPerson ( quotation.getBillingContactPerson () );
                        billingAddress = CustomerDAO.getAddress ( quotation.getBillingAddressId () );
                        billingAddressMap = CustomerDAO.getAddressDetailsMap ( quotation.getBillingAddressId() , quotation.getBillingAddressAsObject () );
                        if( quotationAddress != null )
                        {
                            billingAddress.setPhoneNumber(quotationAddress.getPhoneNumber());
                            billingAddress.setFaxNumber(quotationAddress.getFaxNumber());
                            billingAddress.setEmail(quotationAddress.getEmail());
                        }
                        billingAddress.setContactPerson(subform.getCustomerName());
                        billingAddressMap.put("",SalesOrder.getAddressAsString(billingAddress));
                        session.setAttribute ( "billingAddressMap", billingAddressMap  );
                    }
                    if(shipAddressWithoutContactPerson.trim().equals(""))
                    {

                        subform.setShippingAddressId ( quotation.getShippingAddressId () );
                        Address shippingAddress = quotation.getShippingAddressAsObject();

                        subform.setShippingAddress ( SalesOrder.getAddressAsString ( shippingAddress ) );
                        subform.setShippingAddressId( quotation.getShippingAddressId() );
                        subform.setContactPersonsForShippingAddress ( quotation.getContactPersonsForShippingAddress () );
                        subform.setShippingContactPerson(quotation.getShippingContactPerson());
                        shippingAddressMap = CustomerDAO.getAddressDetailsMap ( quotation.getShippingAddressId() , quotation.getShippingAddressAsObject ());
                        shipAddress = CustomerDAO.getAddress ( quotation.getShippingAddressId () );
                        shipAddress.setContactPerson("");
                        shipAddress.setPhoneNumber("");
                        shipAddress.setCellNumber("");
                        shipAddress.setFaxNumber("");
                        shipAddress.setEmail("");
                        shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                        session.setAttribute ( "shippingAddressMap", shippingAddressMap );
                        subform.setShippingAddresses ( quotation.getShippingAddresses () );
                    }
                    //To get the customer default shipping address when the end user is selected for the quotation.
                    shippingAddresses.add ( CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId() ) ) );
                    subform.setShippingAddresses ( loadShippingAddresses ( shippingAddresses ) );

                    session.setAttribute ( "mfgPartsWithCustomerPartNos", EndUserDAO.loadManfacturingPartNumbersWithEndUserPartNos ( Integer.parseInt ( endUserId ) ) );
                    session.setAttribute ( "mfgPartsWithLabelNumbers", EndUserDAO.loadManfacturingPartNumbersWithEndUserLabelNumbers ( Integer.parseInt ( endUserId ) ) );
                }
                subform.setIsEndCustomerShipAddress( false ); // Added by Veeru on 21st Dec 2004
            }
            session.setAttribute ( "contactPersons", subform.getContactPersons () );
            session.setAttribute ( "billingAddressContactPersons", subform.getContactPersonsForBillingAddress() );
            session.setAttribute ( "shippingAddressContactPersons", subform.getContactPersonsForShippingAddress() );

            lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info );

            /*if ( "".equals ( endUserId ) )
            {
                SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, lineItems, subform.getCustomerId (), subform.getOdmId() );
            }
            else
            {
                SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, lineItems, Integer.parseInt ( endUserId ) );
            }*/

            session.setAttribute ( "lineItems", lineItems );

            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());


            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "shippingMethods", CustomerDAO.loadSalesOrderShippingMethods ( subform.getCustomerId() )  );
            session.setAttribute ( "shippingAddresses", subform.getShippingAddresses () );
            session.setAttribute ( "salesPersons",CustomerDAO.loadAllSalesPersonsforCustomer(subform.getCustomerId () ) ) ;
            session.setAttribute ( "mktgParts", SalesOrderDAO.loadAllMarketingPartNumbers () );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );
            session.setAttribute ( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNosOfCustomer ( subform.getCustomerId (), isSample ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );


            request.setAttribute ( "QuotationForm", subform );

            saveToken ( request );
            return ( mapping.findForward ( "Quotation" ) );
        }
        else if ( "loadODMDetails".equals ( action ) )
        {
            String odmId = request.getParameter ( "odmId" );
            int quotationId = Integer.parseInt(request.getParameter ( "quotationId" ));
            ArrayList lineItems = null;
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, quotationFromMap.getShippingAddresses(), quotationFromMap );
            }
            if ( odmId != null )
            {
                if ( "-1".equals ( odmId.trim () ) )
                {
                    Quotation quotation = QuotationDAO.getQuotationCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );
                    subform.setContactPersons ( quotation.getContactPersons () );
                    subform.setContactPersonsForBillingAddress ( quotation.getContactPersonsForBillingAddress () );
                    subform.setContactPersonsForShippingAddress ( quotation.getContactPersonsForShippingAddress () );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( quotation.getShippingAddressAsObject () ));

                    HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap ( quotation.getShippingAddressId() , quotation.getShippingAddressAsObject ());
                    Address shipAddress = CustomerDAO.getAddress ( quotation.getShippingAddressId () );
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    quotationFromMap.setShippingAddressMap( shippingAddressMap );
                    subform.setShippingAddresses ( quotation.getShippingAddresses () );
                    subform.setEndUser ( "" );
                    subform.setShippingAddressId ( quotation.getShippingAddressId () );
                    subform.setShippingContactPerson ( quotation.getShippingContactPerson () );

                    quotationFromMap.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                    quotationFromMap.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                    quotationFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer(subform.getCustomerId ()) );
                    subform.setShippingMethods( CustomerDAO.loadSalesOrderShippingMethods ( subform.getCustomerId() ) );
                }
                else
                {
                    Quotation quotationCustomerDetails = QuotationDAO.getQuotationCustomerDetails ( Integer.toString ( subform.getOdmId () ) );
                    Quotation quotation = QuotationDAO.getQuotationCustomerDetails ( Integer.toString ( subform.getCustomerId () ) );
                    Address customerShippingAddress = quotation.getShippingAddressAsObject();

                    subform.setContactPersonsForBillingAddress(CustomerDAO.getAllContactPersonsForAddress( quotation.getBillingAddressId() ));
                    subform.setContactPersonsForShippingAddress(CustomerDAO.getAllContactPersonsForAddress( quotationCustomerDetails.getShippingAddressId() ));
                    subform.setEndUser ( "" );
                    subform.setEndUserId( "" );
                    ArrayList shippingAddresses = quotationCustomerDetails.getShippingAddresses ();

                    subform.setShippingAddressId ( quotationCustomerDetails.getShippingAddressId () );
                    subform.setShippingAddress ( SalesOrder.getAddressAsString ( quotationCustomerDetails.getShippingAddressAsObject () ) );

                    subform.setShippingContactPerson( quotationCustomerDetails.getShippingContactPerson() );
                    subform.setContactPersons ( quotation.getContactPersons () );

                    HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap ( subform.getShippingAddressId() , quotationCustomerDetails.getShippingAddressAsObject ());
                    Address shipAddress = CustomerDAO.getAddress(quotationCustomerDetails.getShippingAddressId());
                    shipAddress.setContactPerson("");
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                    shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                    quotationFromMap.setShippingAddressMap( shippingAddressMap );

                    Address address = quotationCustomerDetails.getShippingAddressAsObject();

                    String shipAddressWithoutContactPerson =  SalesOrderAction.getAddressAsString(address);

                    if(shipAddressWithoutContactPerson.trim().equals(""))
                    {
                        subform.setShippingAddressId ( quotation.getShippingAddressId () );
                        subform.setShippingAddress ( SalesOrder.getAddressAsString ( customerShippingAddress ) );
                        subform.setContactPersonsForShippingAddress ( quotation.getContactPersonsForShippingAddress () );
                        subform.setShippingContactPerson(quotation.getShippingContactPerson());
                        shippingAddressMap = CustomerDAO.getAddressDetailsMap ( quotation.getShippingAddressId() , quotation.getShippingAddressAsObject ());
                        shipAddress = CustomerDAO.getAddress ( quotation.getShippingAddressId () );
                        shipAddress.setContactPerson("");
                        shipAddress.setPhoneNumber("");
                        shipAddress.setCellNumber("");
                        shipAddress.setFaxNumber("");
                        shipAddress.setEmail("");
                        shippingAddressMap.put("",SalesOrder.getAddressAsString(shipAddress));
                        quotationFromMap.setShippingAddressMap( shippingAddressMap );
                        subform.setShippingAddresses ( quotation.getShippingAddresses () );
                    }

                    ArrayList defaultShippingAddress = new ArrayList();
                    defaultShippingAddress.add( customerShippingAddress );
                    ArrayList farmatedDefualtShippingAddress = loadShippingAddresses ( defaultShippingAddress );
                    for ( int i = 0; i < farmatedDefualtShippingAddress.size(); i++ )
                    {
                        LabelValueBean bean = ( LabelValueBean ) farmatedDefualtShippingAddress.get( i );
                        shippingAddresses.add( bean );
                    }
                    subform.setShippingAddresses (  shippingAddresses );

                    quotationFromMap.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( quotation.getCustomerId (), quotation.getOdmId(), isSample ) );
                    quotationFromMap.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( quotation.getCustomerId (), quotation.getOdmId(), isSample ) );
                    quotationFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), Integer.parseInt( odmId) ) );
                    subform.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm ( subform.getCustomerId(), Integer.parseInt(odmId ) ) );
                }
                subform.setIsEndCustomerShipAddress( true ); // Added by Veeru on 21st Dec 2004
            }
            quotationFromMap.setContactPersons( subform.getContactPersons () );
            quotationFromMap.setContactPersonsForBillingAddress( subform.getContactPersonsForBillingAddress() );
            quotationFromMap.setContactPersonsForShippingAddress( subform.getContactPersonsForShippingAddress() );
            lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info );

            /*if ( "-1".equals ( odmId ) )
            {
                SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, lineItems, subform.getCustomerId (), subform.getOdmId() );
            }
            else
            {
                SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, lineItems, subform.getCustomerId (), subform.getOdmId() );
                NewSalesOrderDAO.loadOdmLabelNumbersForLineItems ( null, lineItems, subform.getCustomerId (),Integer.parseInt ( odmId ) );
            }*/

            NewSalesOrderDAO.loadCustomerPartNumbersForQuoteLineItems ( null, lineItems, subform.getCustomerId (), subform.getOdmId() );
            session.setAttribute ( "lineItems", lineItems );
            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );
            quotationFromMap.setShippingAddresses( subform.getShippingAddresses() );
            quotationFromMap.setShippingMethods( subform.getShippingMethods() );


            request.setAttribute ( "QuotationForm", subform );

            saveToken ( request );
            return ( mapping.findForward ( "Quotation" ) );
        }
        else if ( "loadShippingAddress".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, quotationFromMap.getShippingAddresses(), quotationFromMap );
            }

            int shippingAddressId = subform.getShippingAddressId();
            int defaultShippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
            Address shipAddress = CustomerDAO.getAddressWithContactPersonDetails ( shippingAddressId );
            HashMap shippingAddressMap = new HashMap();
            if(shipAddress != null)
            {
                /*String shipAddressWithoutContactPerson = SalesOrderAction.getAddressAsString( shipAddress );
                if ( "".equals( shipAddressWithoutContactPerson.trim() ) )
                {
                    if ( defaultShippingAddressId != shippingAddressId )
                    {
                        shippingAddressId = defaultShippingAddressId;
                        subform.setShippingAddressId( shippingAddressId);
                        shipAddress = CustomerDAO.getAddressWithContactPersonDetails ( shippingAddressId );
                    }
                }*/
                subform.setShippingContactPerson( shipAddress.getContactPerson() );
                subform.setShippingAddress ( shipAddress.getAddressAsString ( ));
                shippingAddressMap = CustomerDAO.getAddressDetailsMap ( shippingAddressId, shipAddress);
                shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
            }
            quotationFromMap.setShippingAddressMap( shippingAddressMap );
            quotationFromMap.setContactPersonsForShippingAddress( CustomerDAO.getAllContactPersonsForAddress(  shippingAddressId ) );
            ArrayList lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info );
            session.setAttribute ( "lineItems", lineItems );

            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "allShippingTerms", session.getAttribute ( "allShippingTerms" ) );
            session.setAttribute ( "shippingAddresses", session.getAttribute ( "shippingAddresses" ) );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );

            if ( subform.getOdmId() > 0 )
            {
                quotationFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
            }
            else
            {
                quotationFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomerId ())) ;
            }
            quotationFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm ( subform.getCustomerId(), subform.getOdmId()  ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );

            request.setAttribute ( "QuotationForm", subform );

            saveToken ( request );
            return ( mapping.findForward ( "Quotation" ) );
        }
        else if ( "loadShippingInstructions".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, quotationFromMap.getShippingAddresses(), quotationFromMap );
            }

            subform.setShippingInstructions ( NewSalesOrderDAO.loadSelectedShippingInstructions( null, subform.getShippingInstructionsId() ) );

            ArrayList lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info );
            session.setAttribute ( "lineItems", lineItems );

            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "allShippingTerms", session.getAttribute ( "allShippingTerms" ) );
            session.setAttribute ( "shippingAddresses", session.getAttribute ( "shippingAddresses" ) );

            if ( subform.getOdmId() > 0 )
            {
                quotationFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
            }
            else
            {
                quotationFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomerId ())) ;
            }
            quotationFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm ( subform.getCustomerId(), subform.getOdmId()  ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );

            request.setAttribute ( "QuotationForm", subform );

            saveToken ( request );
            return ( mapping.findForward ( "Quotation" ) );
        }
        else if ( "loadEndCustomerDefualtShippingAddress".equals ( action ) )
        {
            ArrayList shippingList = new ArrayList();
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, shippingList, quotationFromMap );
            }
            quotationFromMap.setShippingAddresses(shippingList);
            int shippingAddressId = 0 ;
            if ( subform.getIsEndCustomerShipAddress() == false )
            {
                NewSalesOrderDAO.loadCustomerAddressesOfType(shippingList, subform.getCustomerId(), "Shipping");
                shippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
            }
            else
            {
                if ( subform.getOdmId() > 0 )
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingList, subform.getOdmId(), "Shipping");
                    shippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getOdmId () );
                }
                else
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingList, subform.getCustomerId(), "Shipping");
                    shippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
                }
            }

            String formContactPerson = null;
            if ( NewSalesOrderDAO.isAddressIdExists( shippingList, subform.getShippingAddressId() ) )
            {
                formContactPerson = subform.getShippingContactPerson();
                shippingAddressId = subform.getShippingAddressId();
            }
            else
            {
                subform.setShippingAddressId(shippingAddressId);
            }

            Address shipAddress = CustomerDAO.getAddress ( shippingAddressId );
            HashMap shippingAddressMap = new HashMap();
            if(shipAddress != null)
            {
                /*String shipAddressWithoutContactPerson = SalesOrderAction.getAddressAsString( shipAddress );
                if ( "".equals( shipAddressWithoutContactPerson.trim() ) )
                {
                    int defaultShippingAddressId = SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId () );
                    if ( defaultShippingAddressId != shippingAddressId )
                    {
                        shippingAddressId = defaultShippingAddressId;
                        subform.setShippingAddressId( shippingAddressId);
                        shipAddress = CustomerDAO.getAddress ( shippingAddressId );
                        subform.setShippingContactPerson( shipAddress.getContactPerson() );
                        formContactPerson = null;
                    }
                }*/
                if ( formContactPerson != null )
                {
                    subform.setShippingContactPerson( formContactPerson );
                }
                else
                {
                    subform.setShippingContactPerson( shipAddress.getContactPerson() );
                }
                ContactPerson shippingContactPerson = CustomerDAO.getAddressContactPersonDetails (shippingAddressId , subform.getShippingContactPerson());
                if( shippingContactPerson != null )
                {
                    shipAddress.setContactPerson(shippingContactPerson.getContactPerson());
                    shipAddress.setPhoneNumber(shippingContactPerson.getPhoneNumber());
                    shipAddress.setCellNumber(shippingContactPerson.getCellNumber());
                    shipAddress.setFaxNumber(shippingContactPerson.getFaxNumber());
                    shipAddress.setEmail(shippingContactPerson.getEmail());
                }
                else
                {
                    shipAddress.setContactPerson( "" );
                    shipAddress.setPhoneNumber("");
                    shipAddress.setCellNumber("");
                    shipAddress.setFaxNumber("");
                    shipAddress.setEmail("");
                }
                subform.setShippingAddress ( shipAddress.getAddressAsString ( ));
                shippingAddressMap = CustomerDAO.getAddressDetailsMap ( shippingAddressId, shipAddress);
                shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
            }
            quotationFromMap.setShippingAddressMap( shippingAddressMap );
            quotationFromMap.setContactPersonsForShippingAddress( CustomerDAO.getAllContactPersonsForAddress(  shippingAddressId ) );
            ArrayList lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info );
            session.setAttribute ( "lineItems", lineItems );

            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "allShippingTerms", session.getAttribute ( "allShippingTerms" ) );
            session.setAttribute ( "shippingAddresses", session.getAttribute ( "shippingAddresses" ) );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );
            if ( subform.getOdmId() > 0 )
            {
                quotationFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
            }
            else
            {
                quotationFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomerId ())) ;
            }
            quotationFromMap.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
            quotationFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm ( subform.getCustomerId(), subform.getOdmId()  ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );

            request.setAttribute ( "QuotationForm", subform );

            saveToken ( request );
            return ( mapping.findForward ( "Quotation" ) );
        }
        else if ( "loadFreightInstructions".equals ( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) )
            {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, quotationFromMap.getShippingAddresses(), quotationFromMap );
            }
            String freightInstructions = null;
            try
            {
                freightInstructions = NewSalesOrderDAO.loadSelectedFreightInstructions( null, subform.getFreightInstructionsId() );
            }
            catch ( ScalarException e )
            {
                System.out.println ( "Exception while loading selected freight Instructions");
                e.printStackTrace();
            }
            subform.setFreightInstructions ( freightInstructions );

            ArrayList lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info );
            session.setAttribute ( "lineItems", lineItems );

            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());

            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "allShippingTerms", session.getAttribute ( "allShippingTerms" ) );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );

            if ( subform.getOdmId() > 0 )
            {
                quotationFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
            }
            else
            {
                quotationFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomerId ())) ;
            }
            quotationFromMap.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm ( subform.getCustomerId(), subform.getOdmId()  ) );
            request.setAttribute ( "Account", subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingAccount () );

            request.setAttribute ( "QuotationForm", subform );

            saveToken ( request );
            return ( mapping.findForward ( "Quotation" ) );
        }
        else if ( "splitLineItems".equalsIgnoreCase( action ) )
        {
            if ( ( subform.getShippingAddressId () == -1 ) && ( session.getAttribute ( "newShippingAddressId" ) != null ) ) {
                subform.setShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newShippingAddressId" ) ) );
                Address address = CustomerDAO.getAddress( subform.getShippingAddressId() );
                loadShippingAddress( address, quotationFromMap.getShippingAddresses(), quotationFromMap );
                session.removeAttribute ( "newShippingAddressId" );
            }
            if ( subform.getOdmId() > 0 )
            {
                quotationFromMap.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) ) ;
            }
            else
            {
                quotationFromMap.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( subform.getCustomerId ())) ;
            }

            session.setAttribute ( "QuotationForm", subform );
            ArrayList lineItems = loadLineItems ( request, subform.getCustomerId (), errors, info );
            session.setAttribute ( "lineItems", lineItems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", request.getAttribute ( "maxLineItemNo" ) );

            subform.setTotalQty ( Integer.parseInt ( ( String ) request.getAttribute ( "totalQty" ) ) );
            subform.setSalesTaxAsDouble(Double.parseDouble((String)request.getAttribute("salesTax")) );
            subform.setSubTotalAsDouble(Double.parseDouble((String)request.getAttribute("subTotal")) );
            subform.setOrderTotalAsDouble(subform.getSubTotalAsDouble()+subform.getFrieghtAsDouble()+subform.getMiscAsDouble()+subform.getSalesTaxAsDouble());
            session.setAttribute ( "totalQty", request.getAttribute ( "totalQty" ) );
            session.setAttribute ( "salesTax", request.getAttribute ( "salesTax" ) );
            session.setAttribute ( "subTotal", request.getAttribute ( "subTotal" ) );
            session.setAttribute ( "orderTotal", Double.toString ( subform.getSalesTaxAsDouble () + subform.getFrieghtAsDouble () + subform.getMiscAsDouble () + subform.getSubTotalAsDouble () ) );
            session.setAttribute ( "tempShippingMethod", subform.getShippingMethod () );
            subform.setOdm( CustomerDAO.getCustomerName( null, subform.getOdmId() ) );
            subform.setEndCustomer( CustomerDAO.getCustomerName( null, subform.getEndCustomerId() ));

            errors = ( HashMap ) request.getAttribute ( "Errors" );
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                return ( mapping.findForward ( "Quotation" ) );
            }

            info = ( HashMap ) request.getAttribute ( "Info" );
            if ( !info.isEmpty () )
            {
                request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
            }
            saveToken ( request );
            return new ActionForward("/splitQuotation.do?isReqFromTransferQuote=true&quotationId="+subform.getQuotationId()+"&customerId="+subform.getCustomerId(), false);
        }
        else if ( request.getParameter ( "quotationId" ) != null )
        {
            String quotationId = request.getParameter ( "quotationId" );

            //Loading the quotation details with out its corresponding customer details
            Quotation quotation = QuotationDAO.loadQuotation ( quotationId, true );

            quotation.setSalesOrderQuoteNo( QuotationDAO.loadQuotationNo( null, quotation.getQuotationId() ) );

            //Loading the customer details pertaining to the customer of this quotation
            Address addressFromQuotation = quotation.getBillingAddressAsObject();
            Quotation quotationCustomerDetails = QuotationDAO.getQuotationCustomerDetails ( Integer.toString ( quotation.getCustomerId () ) );

            //Setting the customer details loaded using the above method into the quotation object
            quotation.setShippingMethods ( quotationCustomerDetails.getShippingMethods () );
            ArrayList shippingAddressesList = new ArrayList();
            if ( quotation.getIsEndCustomerShipAddress() )
            {
                if ( quotation.getOdmId() > 0 )
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingAddressesList, quotation.getOdmId(), "Shipping");
                }
                else
                {
                    NewSalesOrderDAO.loadCustomerAddressesOfType(shippingAddressesList, quotation.getCustomerId(), "Shipping");
                }
            }
            else
            {
                NewSalesOrderDAO.loadCustomerAddressesOfType(shippingAddressesList, quotation.getCustomerId(), "Shipping");
            }
            quotation.setShippingAddresses ( shippingAddressesList );
            quotation.setQuotationNo ( SalesOrderDAO.loadAutomatedSalesOrderNo () );

            if ( quotationMap == null ) {
                    quotationMap = new HashMap();
            }
            quotationMap.put( quotation.getCustomerId()+"", quotation );
            session.setAttribute( "quotationMap", quotationMap ) ;

            //Copying the properties into the form object
            PropertyUtils.copyProperties ( subform, quotation );

            Address customerAddressObject = null;
            customerAddressObject = QuotationDAO.getQuotationAddress ( null,quotation.getQuotationId() );
            if( customerAddressObject == null )
            {
                customerAddressObject = CustomerDAO.getAddress ( quotationCustomerDetails.getBillingAddressId () );
            }
            ContactPerson customerContactPerson = new ContactPerson();
            customerContactPerson.setContactPerson(subform.getCustomerName());
            customerContactPerson.setPhoneNumber(customerAddressObject.getPhoneNumber());
            customerContactPerson.setCellNumber("");
            customerContactPerson.setFaxNumber(customerAddressObject.getFaxNumber());
            customerContactPerson.setEmail(customerAddressObject.getEmail());
            HashMap customerContactPersonMap = (HashMap)CustomerDAO.getContactPersonDetailsMap ( quotation.getCustomerId());
            customerContactPersonMap.put(subform.getCustomerName(),customerContactPerson);
            quotation.setCustomerContactPersonMap( customerContactPersonMap );
            HashMap billingAddressMap = CustomerDAO.getAddressDetailsMap ( quotation.getBillingAddressId() , quotation.getBillingAddressAsObject ());
            addressFromQuotation.setContactPerson( "" );
            addressFromQuotation.setPhoneNumber(customerAddressObject.getPhoneNumber());
            addressFromQuotation.setCellNumber("");
            addressFromQuotation.setFaxNumber(customerAddressObject.getFaxNumber());
            addressFromQuotation.setEmail(customerAddressObject.getEmail());
            billingAddressMap.put("",addressFromQuotation.getAddressAsString());
            quotation.setBillingAddressMap( billingAddressMap );
            HashMap shippingAddressMap = new HashMap();
            int shippingAddressId = quotation.getShippingAddressId ();
            Address shipAddress = CustomerDAO.getAddress ( shippingAddressId );

            shippingAddressMap = CustomerDAO.getAddressDetailsMap ( shippingAddressId , shipAddress );
            shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
            quotation.setShippingAddressMap( shippingAddressMap );
            if ( subform.getOdmId() > 0 )
            {
                subform.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm ( subform.getCustomerId(), subform.getOdmId()  ) );
                quotation.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                quotation.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( subform.getCustomerId (), subform.getOdmId(), isSample ) );
                quotation.setSalesPersons( NewCustomerDAO.loadAllSalesPersonsforCustomerAndOdm( subform.getCustomerId(), subform.getOdmId() ) );
            }
            else if ( !subform.getEndUser ().trim ().equals ( "" ) )
            {
                subform.setEndUserId ( Integer.toString ( EndUserDAO.getEndUserIdByName ( subform.getEndUser (), subform.getCustomerId () ) ) );
                EndUser endUser = EndUserDAO.getEndUserDetails ( Integer.parseInt ( subform.getEndUserId () ) );
                ArrayList shippingAddresses = endUser.getShippingLocations ();
                shippingAddresses.add ( 0, endUser.getShippingAddress () );

                //To get the customer default shipping address when the end user is selected for the quotation.
                shippingAddresses.add ( CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( subform.getCustomerId() ) ) );
                subform.setShippingAddresses ( loadShippingAddresses ( shippingAddresses ) );
                subform.setShippingMethods( CustomerDAO.loadSalesOrderShippingMethods ( subform.getCustomerId() ) );
            }
            else
            {
                subform.setShippingMethods( CustomerDAO.loadSalesOrderShippingMethods ( subform.getCustomerId() ) );
                quotation.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( quotation.getCustomerId (), quotation.getOdmId(), isSample ) );
                quotation.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( quotation.getCustomerId (), quotation.getOdmId(), isSample ) );
                quotation.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer( quotation.getCustomerId () ) );
            }
            session.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
            session.setAttribute ( "freightInstructions", NewSalesOrderDAO.loadFreightInstructions( null ) );

            if ( subform.getShippingMethodName () != null )
            {
                subform.setShippingMethodName ( subform.getShippingMethodName ().trim () );
            }
            if ( subform.getShippingAccount () != null )
            {
                subform.setShippingAccount ( subform.getShippingAccount ().trim () );
            }
            request.setAttribute ( "Account", subform.getShippingMethodName () + "   #   " + subform.getShippingAccount () );
            request.setAttribute ( "Method", subform.getShippingMethodName () + "   #   " + subform.getShippingAccount () );

            session.setAttribute ( "QuotationForm", subform );

            quotation.setContactPersons( subform.getContactPersons () );
            quotation.setContactPersonsForBillingAddress( subform.getContactPersonsForBillingAddress() );
            quotation.setContactPersonsForShippingAddress( subform.getContactPersonsForShippingAddress() );
            session.setAttribute ( "allShippingTerms", quotation.getAllShippingTerms () );
            session.setAttribute ( "allDeliveryTerms", quotation.getAllDeliveryTerms() );

            quotation.setSalesReps( CustomerDAO.loadAllSalesRepsforCustomer( quotation.getCustomerId () ) );
            quotation.setOdmList( CustomerRelationshipDAO.getAllOdmsForCustomer( quotation.getCustomerId()+"" ) );
            quotation.setEndCustomerList( CustomerRelationshipDAO.getAllEndCustomersForCustomer( quotation.getCustomerId()+"" ) ) ;

            quotation.setMfgParts( SalesOrderDAO.loadAllManfacturingPartNosOfCustomer ( quotation.getCustomerId (), isSample ) );

            quotation.setEndCustomerList( CustomerRelationshipDAO.getAllEndCustomersForCustomer( quotation.getCustomerId() + "" ) ) ;

            quotation.setChangedLineItems( QuotationDAO.loadChangedLineItems( null, quotation.getQuotationId(), 1 )  );
            quotation.setPrvApprovedLineItems( QuotationDAO.loadChangedLineItems( null, quotation.getQuotationId(), 0 )  );
            quotation.setShippingMethods( CustomerDAO.loadShippingMethodsForCustomerAndOdm ( subform.getCustomerId(), subform.getOdmId()  ) );

            ArrayList lineItems = QuotationDAO.loadOrderLineItemsWithCustomerPartNo ( Integer.parseInt ( quotationId ), quotation.getCustomerId () );
            request.setAttribute ( "lineItems", lineItems );
            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", Integer.toString ( QuotationDAO.loadMaxLineItemNo ( quotation.getQuotationId () ) ) );
            session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );

            request.setAttribute("QuotationForm",subform);
            saveToken ( request );

            return ( mapping.findForward ( "Quotation" ) );
        }

        return ( mapping.findForward ( "successQuotation" ) );
    }

    public static ArrayList loadLineItems ( HttpServletRequest request, int customerId, HashMap errors, HashMap info ) throws ScalarException
    {
        HttpSession session = request.getSession ();

        String[] lineItem = request.getParameterValues ( "lineItemNo" );
        String[] lineItemId = request.getParameterValues ( "lineItemId" );
        String[] poLineItem = request.getParameterValues ( "poLineItemNo" );
        String[] manufacturingPartNo = request.getParameterValues ( "manufacturingPartNo" );
        String[] quantity = request.getParameterValues ( "quantity" );
        String[] leadTime = request.getParameterValues ( "leadTime" );
        String[] oldQty = request.getParameterValues ( "oldQty" );
        String[] requestDate = request.getParameterValues ( "requestDate" );
        String[] unitPrice = request.getParameterValues ( "unitPriceAsDouble" );
        String[] lineItemDescription = request.getParameterValues ( "lineItemDescription" );
        String[] isApproved = request.getParameterValues ( "isApproved" );
        String[] previousQty = request.getParameterValues ( "previousQuantity" );
        String[] customerPartNo = request.getParameterValues ( "customerPartNo" );
        String[] newCustPartNo = request.getParameterValues ( "newCustomerPartNo" );
        String[] labelNumber = null;
        String[] quotedDate = null;
        String[] quotedQty = null;
        ArrayList lineItemsList = new ArrayList ();
        LineItem lineItemInfo = null;

        String zeroPrice = "";
        String productPrice = "";

        int totalQty = 0;
        float subTotal = 0.0f;
        double salesTax = 0.0;
        double finalSubTotal = 0.0;
        int tempLineItemNo = 0;
        String tempLeadItem="";

        String salesTaxType = request.getParameter ( "salesTaxType" );
        if ( ( salesTaxType.equalsIgnoreCase ( "-1" ) ) == true )
        {
            salesTaxType = request.getParameter ( "newSalesState" );
        }
        float taxvalue = SalesOrderDAO.getTaxValue ( null, salesTaxType );
        Float ff = new Float ( taxvalue );
        double tax = ff.doubleValue ();

        for ( int i = 0; i < manufacturingPartNo.length; i++ )
        {
            if ( lineItem[i].trim ().equals ( "" ) )
            {
                lineItem[i] = "0";
            }
            if ( ( manufacturingPartNo[i] != null ) && ( !manufacturingPartNo[i].equals ( "" ) ) )
            {
                if ( quantity[i].equals ( "" ) )
                {
                    quantity[i] = "0";
                }
                if ( unitPrice[i].equals ( "" ) )
                {
                    unitPrice[i] = "0.0";
                }
                if(leadTime == null || leadTime[i] == null )
                {
                    tempLeadItem = "";
                }
                else
                {
                    tempLeadItem = leadTime[i];
                }
                lineItemInfo = SalesOrderDAO.loadLineItemInfo ( customerId, Integer.parseInt ( lineItem[i] ),
                                                                null,
                                                                manufacturingPartNo[i],
                                                                requestDate[i], tempLeadItem,
                                                                Integer.parseInt ( quantity[i] ),
                                                                StringUtils.formatToFloat ( unitPrice[i] ), 1);
                if ( lineItemInfo == null )
                {
                    errors.put ( "LineItem No " + lineItem[i], " is not having valid partnumbers, please enter valid partnumbers" );
                }

                if ( lineItemInfo == null )
                {
                    lineItemInfo = new LineItem ();
                    lineItemInfo.setLineItemNo ( Integer.parseInt ( lineItem[i] ) );
                    lineItemInfo.setManufacturingPartNo ( manufacturingPartNo[i] );
                    lineItemInfo.setLineItemDescription ( lineItemDescription[i].trim () );
                    lineItemInfo.setLeadTime(leadTime[i]);
                    lineItemInfo.setQuantity ( Integer.parseInt ( quantity[i] ) );
                    lineItemInfo.setUnitPrice ( StringUtils.formatToFloat ( unitPrice[i] ) );
                    lineItemInfo.setUnitPriceAsDouble ( Double.parseDouble ( unitPrice[i] ) );
                    lineItemInfo.setRequestDate ( requestDate[i] );
                    lineItemInfo.setCustomerPartNo ( customerPartNo[i] );
                    lineItemInfo.setLabelNumber( labelNumber[i] );
                }
                else
                {
                    if ( requestDate[i].trim ().length () == 0 )
                    {
                        errors.put ( "LineItem No " + lineItem[i], "Please enter Request  Dock Date." );
                    }
                }

                lineItemInfo.setPoLineItemNo ( Integer.parseInt ( poLineItem[i] ) );

                if ( lineItemId[i] != null )
                {
                    lineItemInfo.setLineItemId ( Integer.parseInt ( lineItemId[i] ) );
                }

                zeroPrice = request.getParameter ( "zeroPrice" + lineItem[i] );
                lineItemInfo.setZeroPrice ( ( zeroPrice != null ) ? true : false );

                productPrice = SalesOrderDAO.loadOldQtyPrice ( null, lineItemInfo.getProductId (), customerId, Integer.parseInt ( oldQty[i] ),lineItemInfo.getRequestDate(), 1);

                if ( ( ( StringUtils.formatToFloat ( unitPrice[i] ) != 0.0 ) || zeroPrice != null ) )
                {
                    if ( ( quantity[i].equalsIgnoreCase ( oldQty[i] ) ) || ( !unitPrice[i].equalsIgnoreCase ( productPrice ) ) )
                    {
                        lineItemInfo.setUnitPrice ( StringUtils.formatToFloat ( Double.toString ( Double.parseDouble ( unitPrice[i] ) ) ) );
                        lineItemInfo.setUnitPriceAsDouble ( Double.parseDouble ( unitPrice[i] ) );
                        double unit_price = Double.parseDouble ( unitPrice[i] );
                        double amt = ( Integer.parseInt ( quantity[i] ) ) * unit_price;

                        lineItemInfo.setAmountAsDouble ( amt );
                    }
                }

                // To find is this lineitem transferable
                lineItemInfo.setIsTransfer ( ( request.getParameter ( "isTransfer" + lineItem[i] ) != null ) ? true : false );
                lineItemInfo.setIsApproved ( ( isApproved[i].equalsIgnoreCase ( "true" ) ? true : false ) );
                lineItemInfo.setIsClose ( ( request.getParameter ( "isClose" + lineItem[i] ) != null ) ? true : false );
                lineItemInfo.setPreviousQuantity ( Integer.parseInt ( previousQty[i].trim () ) );

                if ( request.getParameter ( "isTaxable" + lineItem[i] ) != null )
                {
                    lineItemInfo.setIsTaxable ( true );
                    salesTax = salesTax + ( lineItemInfo.getAmountAsDouble () * ( tax / 100 ) );
                }

                if ( ( lineItemDescription[i] == null ) || ( lineItemDescription[i].trim ().length () == 0 ) )
                {
                    String lItemDesc = null;
                    try
                    {
                        lItemDesc = SalesOrderDAO.getLineItemDescriptionByMfgPartNumber ( manufacturingPartNo[i] );
                        lItemDesc = ( ( lItemDesc == null ) ? "" : lItemDesc );
                        lineItemInfo.setLineItemDescription ( lItemDesc );
                    }
                    catch ( ScalarException se )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SALES_ORDER_DETAILS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Sales Order Details " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, se );
                    }

                }
                else
                {
                    lineItemInfo.setLineItemDescription ( lineItemDescription[i] );
                }

                lineItemInfo.setCustomerPartNo ( customerPartNo[i] );
                lineItemInfo.setNewCustomerPartNo ( newCustPartNo[i] );

                totalQty = totalQty + lineItemInfo.getQuantity ();

                finalSubTotal = finalSubTotal + lineItemInfo.getAmountAsDouble ();
                try
                {
                lineItemInfo.setAmount ( Float.parseFloat ( StringUtils.formatAmountWithNoOfDecimals ( lineItemInfo.getAmount () ) ) );
                }
                catch(NumberFormatException e){}
                request.setAttribute ( "totalQty", Integer.toString ( totalQty ) );

                request.setAttribute ( "salesTax", Double.toString ( salesTax ) );
                request.setAttribute ( "subTotal", Double.toString ( finalSubTotal ) );

                if( Integer.parseInt(lineItem[i]) > tempLineItemNo )
                {
                    tempLineItemNo = Integer.parseInt(lineItem[i]);
                }
                lineItemsList.add ( lineItemInfo );
            }
        }
        request.setAttribute ( "maxLineItemNo", Integer.toString ( tempLineItemNo + 1 ) );

        request.setAttribute ( "Errors", errors );
        request.setAttribute ( "Info", info );

        return lineItemsList;
    }

    private void addNewSalesTaxState ( HttpServletRequest request, HttpSession session, HashMap errors, QuotationForm subform )
    {
        String state1 = null;
        String value1 = null;
        String[] newSalesState = new String[1];
        String[] newSalesTax = new String[1];
        boolean checkstate = false;

        try
        {
            state1 = request.getParameter ( "newSalesState" );
            value1 = request.getParameter ( "newSalesTax" );
            String salesTaxType = request.getParameter ( "salesTaxType" );

            if ( "-1".equals ( salesTaxType ) )
            {

                checkstate = SalesOrderDAO.doesSalesTaxStateExist ( null, state1 );

                if ( checkstate == false )
                {
                    if ( ( state1 != null && state1.length () > 0 ) && ( value1 != null && value1.length () > 0 ) )
                    {
                        newSalesState[0] = state1;
                        newSalesTax[0] = value1;

                        SalesDAO.saveSalesTaxes ( newSalesState, newSalesTax, " " );
                        ArrayList salesStatesList = ( ArrayList ) session.getAttribute ( "salesTaxes" );

                        salesStatesList.add ( new org.apache.struts.util.LabelValueBean ( state1 + " - " + value1, state1 ) );
                        session.setAttribute ( "salesTaxes", salesStatesList );
                        subform.setSalesTaxType ( state1 );

                        value1 = null;
                    }
                }
                else
                {
                    errors.put ( "The State '" + state1 + "' already exists", null );
                    request.setAttribute ( "otherstateadded", "false" );
                    request.setAttribute ( "newsalesstate", state1 );
                    request.setAttribute ( "newsalesvalue", value1 );
                }
            }
        }
        catch ( Exception e )
        {
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_NEW_SALES_TAX_STATE );
            errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
            session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save New Sales Tax State" );
            session.setAttribute ( SessionKeys.ERROR_REPORT, e );
        }
        request.setAttribute ( "Errors", errors );

    }

    private void addNewShippingMethod ( HttpServletRequest request, HttpSession session, HashMap errors, HashMap info, QuotationForm subform, Quotation quotationFromMap )
    {
        String customerId = request.getParameter ( "customerId" );
        String method = null;
        String account = null;
        boolean checkmethodexist = true;
        int customerIdvalue = -1;

        if ( customerId != null )
        {
            session.setAttribute ( "addShippingMethodCustomerId", customerId );
        }
        else
        {
            customerId = ( String ) session.getAttribute ( "addShippingMethodCustomerId" );
        }

        String shippingMethod = subform.getShippingMethod ();
        if ( "-2".equalsIgnoreCase ( shippingMethod ) == true )
        {
            try
            {
                method = request.getParameter ( "newshippingMethod" );
                account = request.getParameter ( "newshippingAccount" );
                customerIdvalue = Integer.parseInt ( customerId );
                checkmethodexist = CustomerDAO.doesShippingMethodExist ( null, customerIdvalue, method, account );

                if ( checkmethodexist == false )
                {
                    if ( !( ( method.equals ( "" ) ) && ( account.equals ( "" ) ) ) )
                    {
                        try
                        {
                            CustomerDAO.insertShippingMethod ( null, customerIdvalue, method, account );
                            //ArrayList shippingMethodList = ( ArrayList ) session.getAttribute ( "shippingMethods" );
                            ArrayList shippingMethodList = quotationFromMap.getShippingMethods();

                            //shippingMethodList.add ( new org.apache.struts.util.LabelValueBean (method, account) );
                            //Modified by Sarada on 25th Feb  2004 to get shiping account along with shipping method
                            shippingMethodList.add ( new org.apache.struts.util.LabelValueBean ( method + "   #   " + account, method + "   #   " + account ) );

                            //session.setAttribute ( "shippingMethods", shippingMethodList );
                            quotationFromMap.setShippingMethods( shippingMethodList );

                            subform.setNewshippingAccount ( "" );
                            subform.setNewshippingMethod ( "" );

                            //This Label is added by Kumaraswamy on Oct 8th, 2004.
                            String newShippingMethodLabel = null;
                            try
                            {
                                newShippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.NewShippingMethod" );
                                if ( newShippingMethodLabel == null )
                                {
                                    newShippingMethodLabel = Labels.DEFAULT_NEW_SHIPPING_METHOD_LABEL;
                                }
                            }
                            catch ( NullPointerException e )
                            {
                                 newShippingMethodLabel = Labels.DEFAULT_NEW_SHIPPING_METHOD_LABEL;
                            }
                            info.put ( newShippingMethodLabel+" has been stored in database successfully", null );
                        }

                        catch ( ScalarException se )
                        {
                            //This Label is added by Kumaraswamy on Oct 15th, 2004.
                            String shippingMethodLabel = null;
                            try
                            {
                                shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                                if ( shippingMethodLabel == null )
                                {
                                    shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                                }
                            }
                            catch ( NullPointerException e )
                            {
                                shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                            }
                            errors.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not Save "+shippingMethodLabel+" Value."+ method );
                            //errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SHIPPED_ORDER + method );
                            se.printStackTrace ();
                        }

                    }
                    subform.setShippingMethodName ( method + "   #   " + account );
                    subform.setShippingAccount ( method + "   #   " + account );
                    subform.setShippingMethod ( method + "   #   " + account );
                    quotationFromMap.setShippingMethod( subform.getShippingMethod() );
                }
                else
                {
                    //These Labels are added by Kumaraswamy on Oct 15th, 2004.
                    String shippingMethodLabel = null;
                    try
                    {
                        shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                        if ( shippingMethodLabel == null )
                        {
                            shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                    errors.put ( method +" "+ shippingMethodLabel+" already Exists ,Please enter another "+shippingMethodLabel+".", null );
                    //errors.put ( method + ERROR_SHIPPING_METHOD_EXISTS, null );
                }
            }
            catch ( Exception e )
            {
                e.printStackTrace ();
            }
        }
    }
    private void setSalesOrderSubTotals ( SalesOrder salesOrder, ArrayList lineItems ) throws ScalarException
    {
        String salesTaxType = salesOrder.getSalesTaxType ();
        double salesTax = 0.0, subTotal = 0.0;
        int totalQty = 0;
        for ( int i = 0; i < lineItems.size (); i++ )
        {
            LineItem lineItem = ( LineItem ) lineItems.get ( i );
            if ( lineItem.getIsTransfer () )
            {
                if ( lineItem.getIsTaxable () )
                {
                    String state = salesTaxType;
                    float taxvalue = SalesOrderDAO.getTaxValue ( null, state );
                    salesTax = salesTax + ( lineItem.getAmountAsDouble () * ( taxvalue / 100 ) );
                }
                totalQty = totalQty + lineItem.getQuantity ();
                subTotal = subTotal + lineItem.getAmountAsDouble ();
            }
        }
        /*
        salesOrder.setTotalQty ( Integer.toString ( totalQty ) );
        salesOrder.setSalesTax ( Float.parseFloat ( Double.toString ( salesTax ) ) );
        salesOrder.setSubTotal ( Float.parseFloat ( Double.toString ( subTotal ) ) );
        salesOrder.setOrderTotal ( salesOrder.getSalesTax () + salesOrder.getFrieght () + salesOrder.getMisc () + salesOrder.getSubTotal () );
        */
        salesOrder.setTotalQty ( Integer.toString ( totalQty ) );
        salesOrder.setSalesTaxAsDouble ( salesTax );
        salesOrder.setSubTotalAsDouble ( subTotal );
        salesOrder.setOrderTotalAsDouble ( salesOrder.getSalesTaxAsDouble () + salesOrder.getFrieghtAsDouble () + salesOrder.getMiscAsDouble () + salesOrder.getSubTotalAsDouble () );

        //Added by Varma 25 Feb 2005 to set the Final Totals for PF version of Sales Order
        salesOrder.setFinalSubTotal ( subTotal  );
        salesOrder.setFinalSalesTax ( salesTax );
        salesOrder.setFinalOrderTotal ( salesOrder.getSalesTaxAsDouble () + salesOrder.getFrieghtAsDouble () + salesOrder.getMiscAsDouble () + salesOrder.getSubTotalAsDouble () );

    }

    private double getClosedLineItemsSubTotal ( ArrayList lineItems )
    {
        double subTotal = 0;
        for ( int i = 0; i < lineItems.size (); i++ )
        {
            LineItem lineItem = ( LineItem ) lineItems.get ( i );
            if ( lineItem.getIsClose() )
            {
                subTotal = subTotal + lineItem.getAmountAsDouble ();
            }
        }
        return subTotal;
    }

    // Added by veeru on 19th May 2004
    private ArrayList loadShippingAddresses ( ArrayList shippingAddresses )
    {
        Address address = null;
        ArrayList shippingList = new ArrayList ();
        for ( int i = 0; i < shippingAddresses.size (); i++ )
        {
            address = ( Address ) shippingAddresses.get ( i );

            int shippingAddressId = address.getAddressId ();

            String addrStr = "";
            /* Commented by Prabhanjan (1 Jun 2004). No need to show contact person in shipping address list box as separate list box is available for shipping contact persons.
            if ( ( address.getContactPerson () != null ) && ( address.getContactPerson ().trim ().length () != 0 ) )
            {
                //addrStr = address.getContactPerson();
                shippingList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getContactPerson (), Integer.toString ( address.getAddressId () ) ) );
            }
            */
            if ( ( address.getAddress1 () != null ) && ( address.getAddress1 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getAddress1 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress2 () != null ) && ( address.getAddress2 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getAddress2 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress3 () != null ) && ( address.getAddress3 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getAddress3 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress4 () != null ) && ( address.getAddress4 ().trim ().length () != 0 ) )
            {
                shippingList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getAddress4 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getCity () != null ) && ( address.getCity ().trim ().length () != 0 ) )
            {
                shippingList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getCity (), Integer.toString ( address.getAddressId () ) ) );
            }

            if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
            {
                addrStr = addrStr + address.getState ();
            }
            if ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) )
            {
                if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
                {
                    addrStr = addrStr + "-";
                }

                addrStr = addrStr + address.getZipCode ();
            }
            if ( ( address.getCountry () != null ) && ( address.getCountry ().trim ().length () != 0 ) )
            {
                if ( ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) ) || ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) ) )
                {
                    addrStr = addrStr + ",";
                }
                addrStr = addrStr + address.getCountry ();
            }
            if ( !( "".equals ( addrStr ) ) )
            {
                shippingList.add ( new org.apache.struts.util.LabelValueBean ( addrStr, Integer.toString ( address.getAddressId () ) ) );
            }
            shippingList.add ( new org.apache.struts.util.LabelValueBean ( "", Integer.toString ( address.getAddressId () ) ) );
        }

        //Set all the shippingAddresses in the salesOrder
        return shippingList;
    }
    //This method is to load only the transfered Line Items for Airgo
    private ArrayList loadTransferedLineItems( ArrayList list )
    {
        ArrayList resultList = new ArrayList ();

        for( int i = 0; i< list.size() ; i++)
        {
            LineItem lineItem = ( LineItem )list.get( i );
            if( lineItem.getIsTransfer() )
            {
               resultList.add( lineItem );
            }
        }
        return resultList;
    }

    public static void loadShippingAddress( Address address, ArrayList shippingList, Quotation quotationFromMap )
    {
          String addrStr = "";

           if ( ( address.getAddress1 () != null ) && ( address.getAddress1 ().trim ().length () != 0 ) )
           {
               shippingList.add ( new org.apache.struts.util.LabelValueBean (
                       address.getAddress1 (), Integer.toString ( address.getAddressId () ) ) );
           }
           if ( ( address.getAddress2 () != null ) && ( address.getAddress2 ().trim ().length () != 0 ) )
           {
               shippingList.add ( new org.apache.struts.util.LabelValueBean (
                       address.getAddress2 (), Integer.toString ( address.getAddressId () ) ) );
           }
           if ( ( address.getAddress3 () != null ) && ( address.getAddress3 ().trim ().length () != 0 ) )
           {
               shippingList.add ( new org.apache.struts.util.LabelValueBean (
                       address.getAddress3 (), Integer.toString ( address.getAddressId () ) ) );
           }
           if ( ( address.getAddress4 () != null ) && ( address.getAddress4 ().trim ().length () != 0 ) )
           {
               shippingList.add ( new org.apache.struts.util.LabelValueBean (
                       address.getAddress4 (), Integer.toString ( address.getAddressId () ) ) );
           }
           if ( ( address.getCity () != null ) && ( address.getCity ().trim ().length () != 0 ) )
           {
               shippingList.add ( new org.apache.struts.util.LabelValueBean (
                       address.getCity (), Integer.toString ( address.getAddressId () ) ) );
           }

           if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
           {
               addrStr = addrStr + address.getState ();
           }
           if ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) )
           {
               if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
               {
                   addrStr = addrStr + "-";
               }
               addrStr = addrStr + address.getZipCode ();
           }
           if ( ( address.getCountry () != null ) && ( address.getCountry ().trim ().length () != 0 ) )
           {
               if ( ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) ) || ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) ) )
               {
                   addrStr = addrStr + ",";
               }
               addrStr = addrStr + address.getCountry ();
           }
           if ( !( "".equals ( addrStr ) ) )
           {
               shippingList.add ( new org.apache.struts.util.LabelValueBean ( addrStr, Integer.toString ( address.getAddressId () ) ) );
           }
           shippingList.add ( new org.apache.struts.util.LabelValueBean ( "", Integer.toString ( address.getAddressId () ) ) );
           ArrayList shippingContactPersons = new ArrayList();
           shippingContactPersons.add( address.getContactPerson() );
           quotationFromMap.setContactPersonsForShippingAddress( shippingContactPersons );
    }


}